import { KcpdShowDb } from "@/kcpd/moudle";
import { DisplaySlotId } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Game, GameComponent } from "@sapi-game/main";
import { KcqdMainState } from "../mainState";
import { Vector3Utils } from "@sapi-game/utils";

export class KcqdDaemon extends GameComponent<KcqdMainState> {
    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        this.subscribe(timer.events.tick, (t) => {
            KcpdShowDb.clear();
            KcpdShowDb.setDisplaySlot(DisplaySlotId.Sidebar);
            KcpdShowDb.set("§b回合时间§r: " + t.remainingTime, 1);
            //清除不是烤肠的人的烤肠
            this.context.players.forEach((p) => {
                if (!p.isSausage) {
                    p.clear(this.state.sausageItem.typeId);
                }
            });
        });
        //tick
        this.subscribe(Game.events.interval, () => {
            //显示烤肠所在的人
            const sausages = this.state
                .getPlayersWithSauage()
                .map(
                    (p) =>
                        `${p.name}(${Vector3Utils.toString(
                            Vector3Utils.intPos(p.player!.location)
                        )})`
                );
            this.context.players.actionbar(
                sausages.length == 0 ? "无" : sausages.join(",")
            );
        });
    }
}
